﻿using SYSoft.Model.Model.Models;
using SYSoft.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SYSoft.Services.SystemManage
{
    public interface ISysUserInfoServices : IBaseServices<sys_User>
    {
        /// <summary>
        /// 通过用户ID获取角色
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        Task<string> GetRoleNameByUserId(int userId);
    }

    public class SysUserInfoServices : BaseServices<sys_User>, ISysUserInfoServices
    {
        IUserRoleServices _userRoleServices;
        IRoleServices _roleServices;
        public SysUserInfoServices(IRoleServices roleServices, IUserRoleServices userRoleServices, IBaseRepository<sys_User> BaseDal) : base(BaseDal)
        {
            this._roleServices = roleServices;
            this._userRoleServices = userRoleServices;
        }

        /// <summary>
        /// 通过用户ID获取角色
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<string> GetRoleNameByUserId(int userId)
        {
            string roleName = "";
            var roleList = await this._roleServices.Query(); //获取所有可用的角色
            var userRole = await _userRoleServices.Query(u => u.UserId == userId);
            if(userRole!=null && userRole.Count>0)
            {
                var arr = userRole.Select(ur => ur.RoleId).ToList();
                var roles = roleList.Where(d => arr.Contains(d.Id));

                roleName = string.Join(',', roles.Select(r => r.RoleName).ToArray());
            }
            return roleName;
        }


    }
}
